package com.example.demo.Controller;

import com.example.demo.dto.Admin.*;
import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.UserResponseDto;
import com.example.demo.entity.Admin;
import com.example.demo.entity.Bookkeeping;
import com.example.demo.entity.User;
import com.example.demo.repository.AdminRepository;
import com.example.demo.security.JwtUtil;
import com.example.demo.service.AdminService;
import com.example.demo.service.BookkeepingService;
import com.example.demo.service.UserService;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

// AdminLoginData class (保持不变)
@lombok.Data
@lombok.AllArgsConstructor
class AdminLoginData {
    private String token;
    @JsonProperty("user")
    private AdminInfoDto user;
}


@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private static final Logger log = LoggerFactory.getLogger(AdminController.class);

    private final AuthenticationManager authenticationManager;
    private final JwtUtil jwtUtil;
    private final AdminRepository adminRepository;
    private final AdminService adminService;
    private final UserService userService;
    private final BookkeepingService bookkeepingService;

    @Autowired
    public AdminController(AuthenticationManager authenticationManager,
                           JwtUtil jwtUtil,
                           AdminRepository adminRepository,
                           AdminService adminService,
                           UserService userService,
                           BookkeepingService bookkeepingService) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
        this.adminRepository = adminRepository;
        this.adminService = adminService;
        this.userService = userService;
        this.bookkeepingService = bookkeepingService;
    }

    // --- 辅助方法 ---
    private UserDetails getUserDetailsFromAuth(Authentication authentication) throws AuthenticationException {
        if (authentication == null || !authentication.isAuthenticated() || authentication.getPrincipal() == null) {
            throw new AuthenticationException("用户未认证或认证信息无效。") {};
        }
        Object principal = authentication.getPrincipal();
        if (!(principal instanceof UserDetails)) {
            throw new AuthenticationException("认证主体不是UserDetails类型。") {};
        }
        return (UserDetails) principal;
    }

    private String getAuthName(Authentication authentication) {
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            return ((UserDetails) authentication.getPrincipal()).getUsername();
        } else if (authentication != null) {
            return authentication.getName();
        }
        return "anonymous";
    }


    // --- 管理员认证与自身管理 (保持不变) ---
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<AdminLoginData>> loginAdmin(@Valid @RequestBody AdminLoginRequestDto loginRequest) {
        try {
            log.info("尝试管理员登录，账号: {}", loginRequest.getAccount());

            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword())
            );

            SecurityContextHolder.getContext().setAuthentication(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            log.info("管理员认证成功: {}", userDetails.getUsername());

            final String token = jwtUtil.generateToken(userDetails);

            Admin admin = adminService.getAdminByAccount(userDetails.getUsername())
                    .orElseThrow(() -> {
                        log.error("已认证的管理员在服务层未找到: {}", userDetails.getUsername());
                        return new EntityNotFoundException("已认证的管理员数据未找到。");
                    });

            AdminInfoDto adminUserDto = new AdminInfoDto(admin.getId(), admin.getAccount(), admin.getUsername());
            AdminLoginData loginData = new AdminLoginData(token, adminUserDto);

            log.info("管理员 {} 登录成功。已生成Token。", admin.getAccount());
            return ResponseEntity.ok(ApiResponse.ok("管理员登录成功", loginData));

        } catch (BadCredentialsException e) {
            log.warn("管理员 {} 登录失败: 账号或密码错误", loginRequest.getAccount());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized("账号或密码错误"));
        } catch (DisabledException e) {
            log.warn("管理员 {} 登录失败: 用户已被禁用", loginRequest.getAccount());
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.forbidden("用户已被禁用"));
        } catch (AuthenticationException e) {
            log.error("管理员 {} 登录认证错误: {}", loginRequest.getAccount(), e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized("认证失败: " + e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 {} 登录时发生意外错误: {}", loginRequest.getAccount(), e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("登录过程中发生内部错误"));
        }
    }

    @PostMapping("/create-admin")
    public ResponseEntity<ApiResponse<AdminInfoDto>> createAdmin(@Valid @RequestBody AdminCreationRequestDto creationRequest) {
        try {
            log.info("请求创建新管理员，账号: {}", creationRequest.getAccount());
            Admin createdAdmin = adminService.createAdmin(creationRequest);
            AdminInfoDto createdAdminInfo = new AdminInfoDto(
                    createdAdmin.getId(),
                    createdAdmin.getAccount(),
                    createdAdmin.getUsername()
            );
            log.info("新管理员 {} 创建成功，ID: {}", createdAdmin.getAccount(), createdAdmin.getId());
            return ResponseEntity
                    .status(HttpStatus.CREATED)
                    .body(ApiResponse.created("管理员创建成功", createdAdminInfo));
        } catch (IllegalArgumentException e) {
            log.warn("创建管理员 {} 失败: {}", creationRequest.getAccount(), e.getMessage());
            return ResponseEntity
                    .status(HttpStatus.CONFLICT)
                    .body(ApiResponse.conflict(e.getMessage()));
        } catch (Exception e) {
            log.error("创建管理员 {} 时发生意外错误: {}", creationRequest.getAccount(), e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("创建管理员时发生内部错误"));
        }
    }

    @GetMapping("/all")
    public ResponseEntity<ApiResponse<List<AdminInfoDto>>> getAllAdmins() {
        try {
            log.info("请求获取所有管理员列表");
            List<Admin> admins = adminService.getAllAdmins();
            List<AdminInfoDto> adminInfoDtos = admins.stream()
                    .map(admin -> new AdminInfoDto(admin.getId(), admin.getAccount(), admin.getUsername()))
                    .collect(Collectors.toList());
            log.info("成功获取并转换了 {} 位管理员的信息。", adminInfoDtos.size());
            return ResponseEntity.ok(ApiResponse.ok("成功获取所有管理员信息", adminInfoDtos));
        } catch (Exception e) {
            log.error("获取所有管理员列表时发生意外错误: {}", e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("获取管理员列表时发生内部错误"));
        }
    }

    @PutMapping("/me/profile")
    public ResponseEntity<ApiResponse<AdminInfoDto>> updateOwnAdminProfile(
            @Valid @RequestBody AdminSelfUpdateDto updateDto,
            Authentication authentication) {
        try {
            UserDetails userDetails = getUserDetailsFromAuth(authentication);
            String currentAdminAccount = userDetails.getUsername();
            log.info("管理员 {} 请求更新自己的个人信息。", currentAdminAccount);

            Admin updatedAdmin = adminService.updateOwnAdminProfile(currentAdminAccount, updateDto);
            AdminInfoDto updatedAdminInfo = new AdminInfoDto(
                    updatedAdmin.getId(),
                    updatedAdmin.getAccount(),
                    updatedAdmin.getUsername()
            );

            log.info("管理员 {} 的个人信息已成功更新。", updatedAdmin.getAccount());
            return ResponseEntity.ok(ApiResponse.ok("管理员个人信息更新成功", updatedAdminInfo));

        } catch (UsernameNotFoundException | EntityNotFoundException e) {
            log.error("更新管理员个人信息失败（用户未找到）: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (IllegalArgumentException e) {
            log.warn("更新管理员个人信息失败: {}", e.getMessage());
            if (e.getMessage().contains("已被")) {
                return ResponseEntity.status(HttpStatus.CONFLICT)
                        .body(ApiResponse.conflict(e.getMessage()));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.badRequest(e.getMessage()));
            }
        } catch (AuthenticationException e) {
            log.warn("更新管理员个人信息失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized(e.getMessage()));
        } catch (Exception e) {
            String authenticatedUser = getAuthName(authentication);
            log.error("更新管理员 {} 个人信息时发生意外错误: {}", authenticatedUser, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("更新管理员个人信息时发生内部错误"));
        }
    }

    @DeleteMapping("/me")
    public ResponseEntity<ApiResponse<Void>> deleteOwnAdminAccount(Authentication authentication) {
        try {
            UserDetails userDetails = getUserDetailsFromAuth(authentication);
            String currentAdminAccount = userDetails.getUsername();
            log.info("管理员 {} 请求删除自己的账户。", currentAdminAccount);

            adminService.deleteOwnAdminAccount(currentAdminAccount);

            log.info("管理员 {} 的账户已成功删除。", currentAdminAccount);
            return ResponseEntity.ok(ApiResponse.okMessage("管理员账户已成功删除。"));

        } catch (UsernameNotFoundException | EntityNotFoundException e) {
            log.error("删除管理员账户失败（用户未找到）: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (IllegalStateException e) {
            log.warn("删除管理员账户操作被阻止: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.forbidden(e.getMessage()));
        } catch (AuthenticationException e) {
            log.warn("删除管理员账户失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized(e.getMessage()));
        } catch (Exception e) {
            String authenticatedUser = getAuthName(authentication);
            log.error("删除管理员 {} 账户时发生意外错误: {}", authenticatedUser, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("删除管理员账户时发生内部错误。"));
        }
    }

    // --- 管理员管理普通用户 (保持不变) ---
    @PostMapping("/users")
    public ResponseEntity<ApiResponse<UserResponseDto>> adminAddUser(
            @Valid @RequestBody AdminUserCreationRequestDto creationRequestDto,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试添加新用户，账号: {}", getAuthName(authentication), creationRequestDto.getAccount());
        try {
            User createdUser = userService.createUserByAdmin(creationRequestDto);
            UserResponseDto responseDto = UserResponseDto.fromUser(createdUser);

            log.info("管理员 '{}' 成功添加新用户 {} (ID: {})", getAuthName(authentication), responseDto.getAccount(), responseDto.getId());
            return ResponseEntity
                    .status(HttpStatus.CREATED)
                    .body(ApiResponse.created("用户创建成功", responseDto));
        } catch (IllegalArgumentException e) {
            log.warn("管理员 '{}' 添加用户 {} 失败: {}", getAuthName(authentication), creationRequestDto.getAccount(), e.getMessage());
            return ResponseEntity
                    .status(HttpStatus.CONFLICT)
                    .body(ApiResponse.conflict(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 添加用户 {} 时发生意外错误: {}", getAuthName(authentication), creationRequestDto.getAccount(), e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("创建用户时发生内部错误"));
        }
    }

    @GetMapping("/users")
    public ResponseEntity<ApiResponse<List<UserResponseDto>>> adminGetAllUsers(Authentication authentication) {
        log.info("管理员 '{}' 请求获取所有普通用户列表。", getAuthName(authentication));
        try {
            List<User> users = userService.getAllUsers();
            List<UserResponseDto> userResponseDtos = users.stream()
                    .map(UserResponseDto::fromUser)
                    .collect(Collectors.toList());

            log.info("成功为管理员 '{}' 获取了 {} 位普通用户的信息。", getAuthName(authentication), userResponseDtos.size());
            return ResponseEntity.ok(ApiResponse.ok("成功获取所有用户信息", userResponseDtos));

        } catch (Exception e) {
            log.error("管理员 '{}' 获取用户列表时发生意外错误: {}", getAuthName(authentication), e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("获取用户列表时发生内部错误"));
        }
    }

    @PutMapping("/users/{userAccount}")
    public ResponseEntity<ApiResponse<UserResponseDto>> adminUpdateUser(
            @PathVariable String userAccount,
            @Valid @RequestBody AdminUserUpdateRequestDto updateRequestDto,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试更新用户 '{}' 的信息。", getAuthName(authentication), userAccount);
        try {
            User updatedUser = userService.updateUserByAdmin(userAccount, updateRequestDto);
            UserResponseDto responseDto = UserResponseDto.fromUser(updatedUser);

            log.info("管理员 '{}' 成功更新用户 '{}' 的信息。", getAuthName(authentication), responseDto.getAccount());
            return ResponseEntity.ok(ApiResponse.ok("用户信息更新成功", responseDto));

        } catch (EntityNotFoundException e) {
            log.warn("管理员 '{}' 更新用户 '{}' 失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (IllegalArgumentException e) {
            log.warn("管理员 '{}' 更新用户 '{}' 失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            if (e.getMessage().contains("已被")) {
                return ResponseEntity.status(HttpStatus.CONFLICT)
                        .body(ApiResponse.conflict(e.getMessage()));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.badRequest(e.getMessage()));
            }
        } catch (Exception e) {
            log.error("管理员 '{}' 更新用户 '{}' 时发生意外错误: {}", getAuthName(authentication), userAccount, e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("更新用户信息时发生内部错误"));
        }
    }

    @DeleteMapping("/users/{userAccount}")
    public ResponseEntity<ApiResponse<Void>> adminDeleteUser(
            @PathVariable String userAccount,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试删除用户 '{}'。", getAuthName(authentication), userAccount);
        try {
            userService.deleteUserByAdmin(userAccount);
            log.info("管理员 '{}' 成功删除用户 '{}'。", getAuthName(authentication), userAccount);
            return ResponseEntity.ok(ApiResponse.okMessage("用户删除成功"));

        } catch (EntityNotFoundException e) {
            log.warn("管理员 '{}' 删除用户 '{}' 失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 删除用户 '{}' 时发生意外错误: {}", getAuthName(authentication), userAccount, e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("删除用户时发生内部错误"));
        }
    }

    // --- 管理员查看用户账本 (保持不变) ---
    @GetMapping("/users/{userAccount}/bookkeeping")
    public ResponseEntity<ApiResponse<List<Bookkeeping>>> adminGetUserBookkeepingRecords(
            @PathVariable String userAccount,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试查询用户 '{}' 的账本数据。", getAuthName(authentication), userAccount);
        try {
            // 使用 adminService 来获取记录，它内部会调用 userService 和 bookkeepingService
            List<Bookkeeping> records = adminService.adminGetUserBookkeepingRecords(userAccount);
            log.info("管理员 '{}' 成功查询到用户 '{}' 的 {} 条账本记录。", getAuthName(authentication), userAccount, records.size());
            if (records.isEmpty()) {
                return ResponseEntity.ok(ApiResponse.ok("该用户尚无账本记录", records));
            }
            return ResponseEntity.ok(ApiResponse.ok("成功获取用户账本记录", records));
        } catch (UsernameNotFoundException | EntityNotFoundException e) { // Catches user not found from adminService
            log.warn("管理员 '{}' 查询用户 '{}' 账本失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 查询用户 '{}' 账本时发生意外错误: {}", getAuthName(authentication), userAccount, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("查询用户账本时发生内部错误"));
        }
    }

    // --- 新增：管理员管理用户账本操作 ---

    @PostMapping("/users/{userAccount}/bookkeeping")
    public ResponseEntity<ApiResponse<Bookkeeping>> adminAddUserBookkeeping(
            @PathVariable String userAccount,
            @Valid @RequestBody AdminBookkeepingCreationRequestDto creationDto,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试为用户 '{}' 添加账本记录。", getAuthName(authentication), userAccount);
        try {
            Bookkeeping newRecord = adminService.adminAddUserBookkeepingRecord(userAccount, creationDto);
            log.info("管理员 '{}' 成功为用户 '{}' 添加账本记录 ID: {}", getAuthName(authentication), userAccount, newRecord.getId());
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ApiResponse.created("管理员成功为用户添加账本记录", newRecord));
        } catch (EntityNotFoundException e) { // 用户未找到
            log.warn("管理员 '{}' 添加用户 '{}' 账本失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (IllegalArgumentException e) { // DTO 校验失败或其他参数错误
            log.warn("管理员 '{}' 添加用户 '{}' 账本失败: {}", getAuthName(authentication), userAccount, e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.badRequest(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 为用户 '{}' 添加账本时发生意外错误: {}", getAuthName(authentication), userAccount, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("为用户添加账本时发生内部错误"));
        }
    }

    @PutMapping("/users/{userAccount}/bookkeeping/{recordId}")
    public ResponseEntity<ApiResponse<Bookkeeping>> adminUpdateUserBookkeeping(
            @PathVariable String userAccount,
            @PathVariable Integer recordId,
            @Valid @RequestBody AdminBookkeepingUpdateRequestDto updateDto,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试修改用户 '{}' 的账本记录 ID: {}", getAuthName(authentication), userAccount, recordId);
        try {
            Bookkeeping updatedRecord = adminService.adminUpdateUserBookkeepingRecord(userAccount, recordId, updateDto);
            log.info("管理员 '{}' 成功修改用户 '{}' 的账本记录 ID: {}", getAuthName(authentication), userAccount, updatedRecord.getId());
            return ResponseEntity.ok(ApiResponse.ok("管理员成功修改用户账本记录", updatedRecord));
        } catch (EntityNotFoundException e) { // 用户未找到 或 账本记录未找到
            log.warn("管理员 '{}' 修改用户 '{}' 账本记录 ID {} 失败: {}", getAuthName(authentication), userAccount, recordId, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (SecurityException e) { // 账本记录不属于该用户
            log.warn("管理员 '{}' 修改用户 '{}' 账本记录 ID {} 失败 (权限不足): {}", getAuthName(authentication), userAccount, recordId, e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.forbidden(e.getMessage()));
        } catch (IllegalArgumentException e) { // DTO 数据问题等
            log.warn("管理员 '{}' 修改用户 '{}' 账本记录 ID {} 失败: {}", getAuthName(authentication), userAccount, recordId, e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.badRequest(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 修改用户 '{}' 账本记录 ID {} 时发生意外错误: {}", getAuthName(authentication), userAccount, recordId, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("修改用户账本记录时发生内部错误"));
        }
    }

    @DeleteMapping("/users/{userAccount}/bookkeeping/{recordId}")
    public ResponseEntity<ApiResponse<Void>> adminDeleteUserBookkeeping(
            @PathVariable String userAccount,
            @PathVariable Integer recordId,
            Authentication authentication) {
        log.info("管理员 '{}' 尝试删除用户 '{}' 的账本记录 ID: {}", getAuthName(authentication), userAccount, recordId);
        try {
            adminService.adminDeleteUserBookkeepingRecord(userAccount, recordId);
            log.info("管理员 '{}' 成功删除用户 '{}' 的账本记录 ID: {}", getAuthName(authentication), userAccount, recordId);
            return ResponseEntity.ok(ApiResponse.okMessage("管理员成功删除用户账本记录"));
        } catch (EntityNotFoundException e) { // 用户未找到 或 账本记录未找到
            log.warn("管理员 '{}' 删除用户 '{}' 账本记录 ID {} 失败: {}", getAuthName(authentication), userAccount, recordId, e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.notFound(e.getMessage()));
        } catch (SecurityException e) { // 账本记录不属于该用户
            log.warn("管理员 '{}' 删除用户 '{}' 账本记录 ID {} 失败 (权限不足): {}", getAuthName(authentication), userAccount, recordId, e.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(ApiResponse.forbidden(e.getMessage()));
        } catch (Exception e) {
            log.error("管理员 '{}' 删除用户 '{}' 账本记录 ID {} 时发生意外错误: {}", getAuthName(authentication), userAccount, recordId, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.internalServerError("删除用户账本记录时发生内部错误"));
        }
    }
}
